package com.bgds.sys.rbac.serviceimpl;

import com.bgds.sys.common.base.BaseDao;
import com.bgds.sys.common.pagevo.Result;
import com.bgds.sys.common.utils.ResultUtil;
import com.bgds.sys.rbac.dao.PermissionDao;
import com.bgds.sys.rbac.dao.RoleDao;
import com.bgds.sys.rbac.domain.Permission;
import com.bgds.sys.rbac.domain.Role;
import com.bgds.sys.rbac.domain.RolePermission;
import com.bgds.sys.rbac.service.RolePermissionService;
import com.bgds.sys.rbac.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * 角色业务实现类
 * @author lj
 */
@Slf4j
@Service
@Transactional(rollbackOn = Exception.class)
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private PermissionDao permissionDao;
    @Override
    public BaseDao<Role, Long> getRepository() {
        return roleDao;
    }

    /**
     * 添加角色
     * @param role
     * @return
     */
    @Override
    public Result<Object> add(Role role){
      Role r=  roleDao.findRoleByName(role.getName());
      if(r!=null){
          return new ResultUtil<>().setErrorMsg("角色已经存在");
      }
     Role role1= roleDao.save(role);
      if(role1==null){
          return new ResultUtil<>().setErrorMsg("新增失败");
      }return new ResultUtil<>().setErrorMsg("新增成功");

    }

    /**
     * 获取所有角色
     * @return
     */
    @Override
    public List<Role> findAll(){


        List<Role> roles=roleDao.findAll();
        for(Role role:roles){
           List<RolePermission> rolePermissions= rolePermissionService.findByRoleId(role.getId());
           List<Permission> permissions=new ArrayList<>();
           for(RolePermission rolePermission:rolePermissions){
               Permission permission= permissionDao.findById(rolePermission.getPermissionId()).get();
               permissions.add(permission);

           }
        }
        return roles;
    }
}
